package com.zhaodui.pl.controller;
import com.zhaodui.order.entity.FxjOrderLogEntity;
import com.zhaodui.pl.entity.FxjPlOveroperEntity;
import com.zhaodui.pl.entity.FxjPlReplanEntity;
import com.zhaodui.pl.service.FxjPlOveroperServiceI;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhaodui.util.fxjUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import org.jeecgframework.core.util.ExceptionUtil;

import org.springframework.stereotype.Controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import static com.xiaoleilu.hutool.date.DateTime.now;

/**   
 * @Title: Controller  
 * @Description: 逾期操作记录
 * @author onlineGenerator
 * @date 2018-11-30 14:41:00
 * @version V1.0   
 *
 */
@Api(value="FxjPlOveroper",description="逾期操作记录",tags="fxjPlOveroperController")
@Controller
@RequestMapping("/fxjPlOveroperController")
public class FxjPlOveroperController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(FxjPlOveroperController.class);

	@Autowired
	private FxjPlOveroperServiceI fxjPlOveroperService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	


	/**
	 * 逾期操作记录列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/zhaodui/pl/fxjPlOveroperList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(FxjPlOveroperEntity fxjPlOveroper,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(FxjPlOveroperEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, fxjPlOveroper, request.getParameterMap());
		try{
		//自定义追加查询条件
		
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.fxjPlOveroperService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除逾期操作记录
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(FxjPlOveroperEntity fxjPlOveroper, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		fxjPlOveroper = systemService.getEntity(FxjPlOveroperEntity.class, fxjPlOveroper.getId());
		message = "逾期操作记录删除成功";
		try{
			fxjPlOveroperService.delete(fxjPlOveroper);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "逾期操作记录删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除逾期操作记录
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "逾期操作记录删除成功";
		try{
			for(String id:ids.split(",")){
				FxjPlOveroperEntity fxjPlOveroper = systemService.getEntity(FxjPlOveroperEntity.class, 
				Integer.parseInt(id)
				);
				fxjPlOveroperService.delete(fxjPlOveroper);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "逾期操作记录删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加逾期操作记录
	 * 
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(FxjPlOveroperEntity fxjPlOveroper, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "逾期操作记录添加成功";
		try{
			fxjPlOveroperService.save(fxjPlOveroper);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "逾期操作记录添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新逾期操作记录
	 * 
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(FxjPlOveroperEntity fxjPlOveroper, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "逾期操作记录更新成功";
		FxjPlOveroperEntity t = fxjPlOveroperService.get(FxjPlOveroperEntity.class, fxjPlOveroper.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(fxjPlOveroper, t);
			fxjPlOveroperService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "逾期操作记录更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 逾期操作记录新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(FxjPlOveroperEntity fxjPlOveroper, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(fxjPlOveroper.getId())) {
			fxjPlOveroper = fxjPlOveroperService.getEntity(FxjPlOveroperEntity.class, fxjPlOveroper.getId());
			req.setAttribute("fxjPlOveroper", fxjPlOveroper);
		}
		return new ModelAndView("com/zhaodui/pl/fxjPlOveroper-add");
	}
	/**
	 * 逾期操作记录编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(FxjPlOveroperEntity fxjPlOveroper, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(fxjPlOveroper.getId())) {
			fxjPlOveroper = fxjPlOveroperService.getEntity(FxjPlOveroperEntity.class, fxjPlOveroper.getId());
			req.setAttribute("fxjPlOveroper", fxjPlOveroper);
		}
		return new ModelAndView("com/zhaodui/pl/fxjPlOveroper-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","fxjPlOveroperController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(FxjPlOveroperEntity fxjPlOveroper,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(FxjPlOveroperEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, fxjPlOveroper, request.getParameterMap());
		List<FxjPlOveroperEntity> fxjPlOveropers = this.fxjPlOveroperService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"逾期操作记录");
		modelMap.put(NormalExcelConstants.CLASS,FxjPlOveroperEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("逾期操作记录列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,fxjPlOveropers);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(FxjPlOveroperEntity fxjPlOveroper,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"逾期操作记录");
    	modelMap.put(NormalExcelConstants.CLASS,FxjPlOveroperEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("逾期操作记录列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<FxjPlOveroperEntity> listFxjPlOveroperEntitys = ExcelImportUtil.importExcel(file.getInputStream(),FxjPlOveroperEntity.class,params);
				for (FxjPlOveroperEntity fxjPlOveroper : listFxjPlOveroperEntitys) {
					fxjPlOveroperService.save(fxjPlOveroper);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	
	@RequestMapping(value="/list/{username}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="逾期操作记录列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<FxjPlOveroperEntity>> list(@PathVariable("username") String username, @RequestParam int pageNumber, @RequestParam int pageSize, HttpServletRequest request) {
		if(pageSize > Globals.MAX_PAGESIZE){
			return Result.error("每页请求不能超过" + Globals.MAX_PAGESIZE + "条");
		}
		CriteriaQuery query = new CriteriaQuery(FxjPlOveroperEntity.class);
		String orgcode = "";
		try{
			if(StringUtil.isNotEmpty(request.getParameter("cusName"))){
				query.like("cusName","%"+request.getParameter("cusName")+"%");
			}
			if(StringUtil.isNotEmpty(request.getParameter("cusMobile"))){
				query.like("cusMobile","%"+request.getParameter("cusMobile")+"%");
			}
			if(StringUtil.isNotEmpty(request.getParameter("orderNo"))){
				query.like("orderNo","%"+request.getParameter("orderNo")+"%");
			}
			if(StringUtil.isNotEmpty(request.getParameter("bpmStatus"))){
				query.eq("bpmStatus",request.getParameter("bpmStatus"));
			}
			if (StringUtil.getStringLen(username)>20){
				query.eq("createBy",username);
			}else {
				TSUser task = fxjUtil.getsysorgcode(username);
				if (task != null) {
					orgcode = task.getCurrentDepart().getSysOrgCode();
				}
				query.like("sysOrgCode", orgcode + "%");
			}

		}catch (Exception e){
		}
		query.add();
		List<FxjPlOveroperEntity> listsize = this.fxjPlOveroperService.getListByCriteriaQuery(query,false);
		query.setCurPage(pageNumber<=0?1:pageNumber);
		query.setPageSize(pageSize<1?1:pageSize);
		query.add();
		List<FxjPlOveroperEntity> listFxjPlOveropers = this.fxjPlOveroperService.getListByCriteriaQuery(query,true);
		return Result.success(listFxjPlOveropers,(long)listsize.size());
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取逾期操作记录信息",notes="根据ID获取逾期操作记录信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {
		FxjPlOveroperEntity task = fxjPlOveroperService.get(FxjPlOveroperEntity.class, Integer.parseInt(id));
		if (task == null) {
			return Result.error("根据ID获取逾期操作记录信息为空");
		}
		return Result.success(task);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建逾期操作记录")
	public ResponseMessage<?> create(@ApiParam(name="逾期操作记录对象")@RequestBody FxjPlOveroperEntity fxjPlOveroper, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<FxjPlOveroperEntity>> failures = validator.validate(fxjPlOveroper);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{
			FxjOrderLogEntity fxjOrderLogEntity = new FxjOrderLogEntity();
			fxjOrderLogEntity.setOrderNo(fxjPlOveroper.getOrderNo());
			fxjOrderLogEntity.setLogUser(fxjPlOveroper.getUpdateBy());
			fxjOrderLogEntity.setLogDate(now());
			fxjOrderLogEntity.setSysOrgCode(fxjPlOveroper.getSysOrgCode());
//			fxjOrderLogList.add(fxjOrderLogEntity);
			fxjOrderLogEntity.setBpmStatus(fxjPlOveroper.getBpmStatus());
			try{
				fxjOrderLogEntity.setLogContent("逾期操作录入");//审批意见
			}catch (Exception e){

			}
			systemService.save(fxjOrderLogEntity);

			fxjPlOveroperService.save(fxjPlOveroper);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("逾期操作记录信息保存失败");
		}
		return Result.success(fxjPlOveroper);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新逾期操作记录",notes="更新逾期操作记录")
	public ResponseMessage<?> update(@ApiParam(name="逾期操作记录对象")@RequestBody FxjPlOveroperEntity fxjPlOveroper) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<FxjPlOveroperEntity>> failures = validator.validate(fxjPlOveroper);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{

			FxjPlOveroperEntity t = fxjPlOveroperService.get(FxjPlOveroperEntity.class, fxjPlOveroper.getId());

			FxjOrderLogEntity fxjOrderLogEntity = new FxjOrderLogEntity();
			fxjOrderLogEntity.setOrderNo(t.getOrderNo());
			fxjOrderLogEntity.setLogUser(fxjPlOveroper.getUpdateBy());
			fxjOrderLogEntity.setLogDate(now());
			fxjOrderLogEntity.setSysOrgCode(t.getSysOrgCode());
//			fxjOrderLogList.add(fxjOrderLogEntity);
			fxjOrderLogEntity.setBpmStatus(fxjPlOveroper.getBpmStatus());
			try{
				fxjOrderLogEntity.setLogContent("逾期操作编辑");//审批意见
			}catch (Exception e){

			}
			systemService.save(fxjOrderLogEntity);

			fxjPlOveroper.setOverdueDate(now());
			fxjPlOveroper.setUpdateDate(now());
			MyBeanUtils.copyBeanNotNull2Bean(fxjPlOveroper, t);
			fxjPlOveroperService.saveOrUpdate(t);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("更新逾期操作记录信息失败");
		}

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success("更新逾期操作记录信息成功");
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除逾期操作记录")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" , id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			fxjPlOveroperService.deleteEntityById(FxjPlOveroperEntity.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("逾期操作记录删除失败");
		}

		return Result.success();
	}
}
